package org.iot.iotserver.netty.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.iot.iotserver.netty.command.*;
import org.iot.iotserver.service.IIOTCommonService;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务端数据处理
 */
public class YIOTServerHandler extends AbstractIOTServerHandler {

    private static final Log log = LogFactory.get();

    private final List<IYCommandExecutor> commandExecutors = new ArrayList<>();

    public YIOTServerHandler(IIOTCommonService iotCommonService) {
        super(iotCommonService);
        this.commandExecutors.add(new LEDCommandExecutor(iotCommonService));
        this.commandExecutors.add(new DataReportingCommandExecutor(iotCommonService));
        this.commandExecutors.add(new ReadDeviceInfoCommandExecutor(iotCommonService));
        this.commandExecutors.add(new RegisterCommandExecutor(iotCommonService));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String receiveData) throws Exception {
        final String str = receiveData.trim();

        if(StrUtil.isEmpty(str)) {
            return;
        }

        final Channel channel = channelHandlerContext.channel();
        int count = 0;

        for (IYCommandExecutor commandExecutor : this.commandExecutors) {
            try {
                if(commandExecutor.isMatching(str)) {
                    String result = commandExecutor.execute(channelHandlerContext, getArgs(str));
                    channel.writeAndFlush(result);
                    count++;
                }
            } catch (Exception e) {
                count++;
                e.printStackTrace();
                channel.writeAndFlush("ERROR");
            }
        }

        if(count <= 0) {
            channel.writeAndFlush("no command execute!!!\r\n");
        }

        super.channelRead0(channelHandlerContext, str);
    }
}
